const mysql = require("mysql");
const createTable = require("./sqlCode");
//数据库配置
let config = {
  host: "localhost",
  port: "3306",
  user: "exapp",
  password: "123456",
  database: "exapp",
};
// 根据IP指定配置文件
ipConfig = (ip) => {
  if (ip === "192.168.34.56") {
    console.log(logsucc("USE LINUX CONFIG"));
    config = {
      host: "192.168.34.90",
      port: "3306",
      user: "root",
      password: "123456",
      database: "exapp",
    };
  }
};
//第一种方式
//连接池对象                    ↓sqlArr是一个占位符，填补第一个参数sql中?的值，sqlArr也可不传默认false，则第二个参数为执行结果回调
/*   sqlConnect: function (sql, sqlArr = false, callBack) {
            //建立一个连接，连接参数为配置好的config对象
            var pool = mysql.createPool(this.config);
            pool.getConnection((err, data) => {
              if (err) {
                console.log(err, "sql:连接失败");
                return;
              }
              console.log("sql:连接成功");
              //事件驱动回调
              data.query(sql, sqlArr, callBack);
              //释放连接
              data.release();
            });
          }, */
//第二种方式
//promise回调

SySqlConnect = (sySql, sqlArr = false) => {
  return new Promise((resolve, reject) => {
    //建立一个连接，连接参数为配置好的config对象
    var pool = mysql.createPool(config);
    pool.getConnection((err, data) => {
      if (err) return reject(err);
      //事件驱动回调，连接成功后操作数据库
      data.query(sySql, sqlArr, (err, data) => {
        if (err) return reject(err);
        resolve(data);
      });
      //释放连接
      data.release();
    });
  }).catch((err) => {
    // console.log(err);
    console.log(logerr("Mysql Error!!", err.code));
    if (err.errno === 1064) return { msg: "参数错误", err };
    if (err.errno === -4078) return { msg: "数据库连接失败", err };
    return { msg: "数据库错误", err };
  });
};
createTableFun = async () => {
  const selectEnd = await SySqlConnect(createTable.select_table); // 查询 'exapp'库中表尾名为‘_table’ 名称表单
  if (selectEnd.hasOwnProperty("err")) return console.log(selectEnd);
  // console.log(selectEnd);
  console.log(logbgsucc("Mysql Connect OK!"));
  //查询users_table总行数存储到内存
  const total_rows = await SySqlConnect(createTable.selectUsersRows); // 查询表行数
  // console.log(total_rows.hasOwnProperty("err"));
  if (total_rows.hasOwnProperty("err")) {
    console.log(logerr("users_table行数查询失败", total_rows.err));
  } else {
    countRows = total_rows[0]["count(id)"];
    console.log(logsucc("users_table rows:" + countRows));
  }
  
  // 建表
  const tableList = [
    "users_table",
    "article_table",
    "code_table",
    "usersdelete_table",
  ];
  if (selectEnd.length === tableList.length) return console.log(logsucc("..."));;
  let errNum = 0;
  console.log(logsucc("开始建表..."));
  for (let i = 0; i < tableList.length; i++) {
    let tableKeys = tableList[i];
    const getTable = await SySqlConnect(createTable[tableKeys]);
    if (getTable.err) {
      let logmsg = `数据表创建失败=>[${tableKeys}]=> ${getTable.err.sqlMessage} ${getTable.err.errno}`;
      if (getTable.err.sqlMessage === `Table '${tableKeys}' already exists`)
        logmsg = `数据表已经存在=>[${tableKeys}]`;
      console.log(logwarn(logmsg));
    } else {
      errNum += 1;
      console.log(logsucc(`数据表创建成功=>[${tableKeys}]`));
    }
  }
  console.log(logwarn(`成功${errNum},失败${tableList.length - errNum}`));
  console.log(logsucc("..."));
};
//暴露
module.exports = {
  mysql,
  ipConfig,
  SySqlConnect,
  createTableFun,
};
